import React from 'react';
import { Row, Col, Select, Input, Button, Cascader, Table, Card, Pagination, message, Icon,Form, Modal, Tooltip ,Message} from 'antd';
import './index.less';
import { deleteList, getInfo, getOldInfo, selectInfoByTime, exportElderly} from '../../services/api';
import { connect } from 'dva';
import { formatCascader } from '../../common/common';
import Modals from './addModal';
import DistributeModal from './distributeModal';
import {fileDownLoad} from '../../config/index';

const Option = Select.Option;

class OldMan extends React.Component {
	state = {
		dataSource: [],   //数据列表
		pageSize:10,  //每页显示条数
		pageCurrent:1,   //当前页
		sum:0,   //总条数
		selectedRowKeys: [], // 选中的数据下标
		loading: false,
		infoArr:{},  //详情数组
		show:'add',   //'add'为新增  'upData'为修改  'detail'为查看详情

        //查询条件
		area:'',   
		name:'',
		phone:'',
		content:'',
		servicePeople:'',
		historyList: [],
		selsectOldId: '',

		dataInfo:'',   //老人信息导出路径
	};

	componentDidMount(){
		this.props.dispatch({type: 'example/setServicePersons',res:this.props.servicePersons});   //服务负责人
		this.props.dispatch({type: 'example/setServiceType',res:this.props.serviceType});  //服务内容
		this.props.dispatch({type: 'example/setAreaInfo',res:this.props.areaInfo});  //区域
	    this.getInfo();  //页面初始请求老人列表
	}
	
	//翻页触发的事件
	onchange = (page) => {
		this.setState({
			pageCurrent: page,
			selectedRowKeys: [],
		},()=>{
		this.getInfo({pageCurrent:this.state.pageCurrent,pageSize:this.state.pageSize});
		});
	  }

	//页码数改变触发的事件
	onShowSizeChange = (current, pageSize) => {
		this.setState({
			pageSize: pageSize,
			pageCurrent: current,
			selectedRowKeys: [],
		},()=>{
			this.getInfo({pageCurrent:this.state.pageCurrent,pageSize:this.state.pageSize})
		});
	  }

	  //选框触发的事件
	  onSelectChange = (selectedRowKeys) => {
		this.setState({ 
			selectedRowKeys
		 },()=>{
		 });
	  }

	  //新增，修改
	  operateModal_(flag){
		flag === 'add' ? 
		this.setState({show:'add',infoArr:{}}): 
		flag === 'upData' ? 
		this.setState({show:'upData'}) :
		 this.setState({show:'detail'})
		  
		  this.props.dispatch({type: 'example/setAddModal', res: !this.props.addModal});
	  }
	  //分配
	  operateModals(){	
		if(this.state.selectedRowKeys.length <= 0){
			message.error('请至少选择一条数据');
			return;
		}
		 this.props.dispatch({type: 'example/setDistributeModal', res: !this.props.distributeModal});
	 }
	

	//列表数据
	getInfo = async()=>{
		this.setState({loading:true})
		const response  = await getInfo({
			fContent:this.state.content?this.state.content:'' ,
			fName:this.state.name? this.state.name : '',
			fPhone:this.state.phone?this.state.phone:'',
			fServiceStaff:this.state.servicePeople ? this.state.servicePeople : '',
			fStreetCommunity:this.state.area ? this.state.area[this.state.area.length - 1] : '',
			pageCurrent:this.state.pageCurrent,
			pageSize:this.state.pageSize,
		});
		if(response.code === 200){
			this.setState({
				dataSource:response.data.dataList,
				sum:response.data.totalNumber,
				loading:false,
				selectedRowKeys:[]   //选框置空
			})
		} else {
			this.setState({loading:false})
			response.msg && message.error(response.msg);
		}
	}

	//导出老人信息
	async exportElderly(){
		const response = await exportElderly({
			fContent:this.state.content?this.state.content:'' ,
			fName:this.state.name? this.state.name : '',
			fPhone:this.state.phone?this.state.phone:'',
			fServiceStaff:this.state.servicePeople ? this.state.servicePeople : '',
			fStreetCommunity:this.state.area ? this.state.area[this.state.area.length - 1] : '',
			pageCurrent:0,
			pageSize:0,
		});
		if(response.code === 200){
           this.setState({
			   dataInfo:response.data,
		       selectedRowKeys: [],		   
		   },()=>{
			fileDownLoad(this.state.dataInfo,'老人台账表','xls');
			Message.success('信息导出成功');
		   })
		} else {
			response.msg && message.error(response.msg)
		  }
	}

	//查看详情
	async getOldInfo(id){
		const response = await getOldInfo(id);
		if(response.code === 200){
          this.setState({
			  infoArr:response.data,
		  })
		} else {
			response.msg && message.error(response.msg);
		}
	}
	//点击查看，调用详情接口，触发modal出现
	async info(id){
		await this.getOldInfo(id);
		this.operateModal_('detail');
	}

	//点击修改，调用详情接口，触发modal出现
	//修改
    async info_(id){
		await this.getOldInfo(id);
		this.operateModal_('upData');
	}

	/** 
	 * 打开查看历史模态框
	*/
	openHistory = async (id) => {
		await this.setState({
			selsectOldId: id,
			show: 'history'
		});
		await this.getHistory();
		this.props.dispatch({type: 'example/setAddModal', res: !this.props.addModal});
	}

	/** 
	 * 获取服务历史记录
	*/
	getHistory = async (params) => {
		let param = params ? params : {
			fBeginnTime: '',
			fEndTime: '',
			fId: this.state.selsectOldId,
		}
		let res = await selectInfoByTime(param);
		if(res.code === 200) {
			this.setState({
				historyList: res.data
			});
			return;
		}
		this.setState({
			historyList: []
		});
	}

	

	//删除
	del(){
		if(this.state.selectedRowKeys.length <= 0){
			message.warning('请至少选择一条您要进行操作的数据');
			return;
		}
		Modal.confirm({
			title: '是否确定删除已勾选数据?',
			content: `已选择${this.state.selectedRowKeys.length}条数据, 删除后将无法追回`,
			okText: '确认',
			okType: 'primary',
			cancelText: '取消',
			onOk: () => this.delete()
		  });
	}
	async delete(){
		const response = await deleteList(this.state.selectedRowKeys);
		if(response.code === 200){
			this.setState({
				selectedRowKeys: [],
				
			  },()=>{
				this.getInfo();
			  });
			  Message.success('删除成功')
		} else {
			response.msg && message.error(response.msg);
		}
	}


	handleChange(value) {
		this.setState({
			content: JSON.stringify(value),
		  });
	}

	forceUpdate_ = () => {
		this.forceUpdate();
	}

	

	render() {
		const columns = [{
			title: '老人姓名',
			className: 'columnTitle',
			dataIndex:'fElderlyName',

			width: 170
		}, {
			title: '老人电话',
			className: 'columnTitle',
			dataIndex:'fElderlyPhone',
			width: 170
		}, {
			title: '街办区域',
			className: 'columnTitle',
			dataIndex:'fStreetCommunity',
			width: 170
		},{
			title: '服务内容',
			className: 'columnTitle',

			dataIndex:'fContentName',
			width: 170	
		}, {
			title: '服务次数',
			className: 'columnTitle',
			dataIndex:'fServiceTimes',
			render:(val) => val === 0 ? '--' : `${val}次`,
			width: 170
		}, {
			title: '剩余服务次数',
			className: 'columnTitle',
			dataIndex:'fSurplusTimes',
			render:(val) => val === 0 ? '--' : `${val}次`,
			width: 170
		} ,{
			title: '本月是否服务',
			className: 'columnTitle',
			dataIndex:'isRecord',
			width: 170,
			render:(val)=>{
              return(
				  <div>
                    {
					  val === 0 ? 
					  <Icon type="close-circle-o" style={{color:'#FF4C4E'}} /> : 
					  <Icon type="check-circle-o" style={{color:'#3691FF'}}/>
					}
				  </div> 
			  )
			}
		}, {
			title: '服务负责人',
			className: 'columnTitle',
			dataIndex:'fServiceName',
			width: 170
		}, {
			title: '负责人电话',
			className: 'columnTitle',
			dataIndex:'fServicePhone',
			width: 170
		}, {
			title: '操作',
			className: 'columnTitle',
			width: '100px',
			fixed: 'right',
			render:(val)=>{
             return(
				 <div>
					<Tooltip title="修改">
				   		<Icon type="form" style={{marginRight:10,color:"#3890FF"}} onClick={()=>this.info_(val.fId)} className="do"/>
					</Tooltip>
					<Tooltip title="查看">
  			       		<Icon type="bars" onClick={()=>this.info(val.fId)} style={{marginRight:10,color:"#3890FF"}} className="do"/>
				   	</Tooltip>
					<Tooltip title="历史记录">
  			       		<Icon type="dot-chart" onClick={()=>this.openHistory(val.fId)} style={{marginRight:10,color:"#3890FF"}} className="do"/>
					</Tooltip>
				 </div>
			 )
			}
		}];

		const { loading, selectedRowKeys } = this.state;
		const rowSelection = {
		  selectedRowKeys,
		  onChange: this.onSelectChange,
		};
		return (
			<div style={{padding: '20px 40px'}}>
				<Card>
				<div style={{display: 'flex'}}>
					<Row  className='searchDiv searchCard' type="flex" justify="space-around">
						<Col span={4} className='searchDivChildren'>
							<Row style={{marginBottom: 10}}>
								<span className='titleSpan'>街办区域:</span>
							</Row>
							<Row>
								<Cascader style={{width: '100%'}} options={formatCascader(this.props.areaInfo, 'fId', 'fName', 'children')} onChange={(val)=>{this.setState({area:val})}} placeholder="请选择..." changeOnSelect/>
							</Row>
						</Col>
						<Col span={4} className='searchDivChildren'>
							<Row  style={{marginBottom: 10}}>
								<span className='titleSpan'>老人姓名:</span>
							</Row>
							<Row>
								<Input onChange={this.getName} placeholder="请输入..." value={this.state.name} onChange={(e)=>{this.setState({name:e.target.value})}}/>
							</Row>
						</Col>
						<Col span={4} className='searchDivChildren'>
							<Row style={{marginBottom: 10}}>
								<span className='titleSpan'>老人电话:</span>
							</Row>
							<Row>
								<Input onChange={this.getPhone} placeholder="请输入..." value={this.state.phone} onChange={(e)=>{this.setState({phone:e.target.value})}}/>
							</Row>
						</Col>
						<Col span={4} className='searchDivChildren'>
							<Row style={{marginBottom: 10}}>
								<span className='titleSpan'>服务内容:</span>
							</Row>
							<Row>
								<Select onChange={(value)=>{this.setState({content:value})}} style={{width:'100%'}} placeholder="请选择..." allowClear> 
								{
									this.props.serviceType.map((item)=>{
										return(
											<Option value={item.fId} key={item.fId}>{item.fName}</Option>
										)
									})
								}
  								</Select>
							</Row>
						</Col>
						<Col span={4} className='searchDivChildren'>
							<Row style={{marginBottom: 10}}>
								<span className='titleSpan'>服务负责人:</span>
							</Row>
							<Row>
								<Select onChange={(value)=>{this.setState({servicePeople:value})}} style={{width:'100%'}} placeholder="请选择..." allowClear> 
								{
									this.props.servicePersons.map((item)=>{
										return(
											<Option value={item.fId} key={item.fId}>{item.fName}</Option>
										)
									})
								}
  								</Select>
							</Row>
						</Col>
					</Row>
					<div style={{height: 67,lineHeight: '100px'}}>
					<Button type="primary" onClick={()=>this.getInfo()}>查询</Button>
					</div>
				</div>
				</Card>

				<div className="search">
				  <Button  onClick={()=>this.operateModal_('add')}  type="primary" >新增</Button>
				  <Button type="danger"  onClick={()=>this.del()} >删除</Button>
				  <Button onClick={()=>this.operateModals()} style={{backgroundColor:'#F5C66B',color:'white'}} className="dev">分配</Button>
				  <Button onClick={()=>this.exportElderly()} style={{background:'#bb9ffa',color:'white'}}>导出</Button>
				</div>

				<Card style={{marginTop: 10}}>
					<Table
					    rowKey="fId"
						style={{marginBottom: 20}}
						columns={columns}
						dataSource={this.state.dataSource}
						pagination={false}
						loading={loading}
						locale={{
							emptyText: '暂无数据'
						}}
						rowSelection={rowSelection}
					/>
					<Pagination size="small" 
					    total={this.state.sum} 
					    current={this.state.pageCurrent}
					    pageSize={this.state.pageSize}
						showSizeChanger
						showQuickJumper
						showTotal={(total)=>(<span>共{total}条</span>)}
						onChange={this.onchange}
						onShowSizeChange={this.onShowSizeChange}
					/>
				</Card>

				{/* 修改，增加，查看详情 */}
				<Modals upData_={this.forceUpdate_} visable={this.props.addModal} operateModal={()=>this.operateModal_()} area={this.props.dispatch} show={this.state.show} valueArr={this.state.infoArr} getInfo={()=>this.getInfo()}  areaInfo={this.props.areaInfo} selsectOldId={this.state.selsectOldId} historyList={this.state.historyList} queryHistory={this.getHistory}/> 

				{/* 分配人员 */}
				<DistributeModal visable={this.props.distributeModal} operateModal={()=>this.operateModals()} serviceP={this.props.servicePersons}  selectedRowKeys={this.state.selectedRowKeys} dataSource={this.state.dataSource} upData={this.forceUpdate_} getInfo={this.getInfo}/>
			</div>
		)
	}
}

const service = Form.create()(OldMan)
export default connect((state)=>({
	oldDetailModal: state.example.oldDetailModal,
	addModal: state.example.addModal,
	distributeModal: state.example.distributeModal,
	areaInfo: state.example.areaInfo,
    serviceType:state.example.serviceType,
    servicePersons:state.example.servicePersons,
}))(service)


